package com.sast.sql;

import java.sql.*;
import java.text.SimpleDateFormat;

public class DataBase {
	// MySQL 8.0 以上版本 - JDBC 驱动名及数据库 URL
    static String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";  
    static final String DB_URL = "jdbc:mysql://localhost:3306/rfid_db?useSSL=false&serverTimezone=UTC";
    // 数据库的用户名与密码
    static final String USER = "root";
    static final String PASS = "368212";
    
    Connection conn = null;
    Statement stmt = null;
    
	public DataBase() {
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
			conn = DriverManager.getConnection(DB_URL, USER, PASS);
            stmt = conn.createStatement();
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}
	}

	public void getData(String tableName) {
		try {
			ResultSet rs = stmt.executeQuery("SELECT * FROM "+ tableName);
			//打印数据表
			while (rs.next()) {
				Timestamp ts= rs.getTimestamp("datetime");
				String datetime = ts ==null? "": new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(ts);
				// 输出数据
				System.out.print("id: " + rs.getInt("id"));
				System.out.print(", epc_id: " + rs.getString("epc_id"));
				System.out.println(", datetime: " + datetime);
				// 完成后关闭
				rs.close();
				stmt.close();
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void update(String sql,Object ... args){
		if (conn != null) {
			PreparedStatement ps;
			try {
				ps = conn.prepareStatement(sql);
				for(int i = 0;i < args.length;i++){
					ps.setObject(i + 1, args[i]);
				}
				//执行
				ps.execute();
				ps.close();
				conn.close();
			} catch (SQLException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}

		}

	}
}
/*
 * String sql = "insert into  Inventory_Log(epc_id,datetime)values(?,?)";update(sql,4,90);
 * String sql = "update Inventory_Log set epc_id = ? where datetime = ?";update(sql,4,90);
 * String sql = "delete from Inventory_Log where epc_id = ?";update(sql,4);
*/